var http = require("http");
var path = require("path");
var fs = require("fs");
var config = require("./config.json");
var mime = require('mime-types')
//文件缓存区
var fileCache = {};
//路径解析
function filePathParse(file_path) {
	file_path || (file_path = config.default_page);
	file_path = path.join(__dirname, "..", config.folder, file_path);
	return file_path;
}
var file_404 = fs.readFileSync(fs.filePathParse(config["404_file"]));

/*
 * 配置
 */
var port = 2222;

http.all("/*", function(req, res) {
	var file_path = filePathParse(req.params[0]);
	var cache_data = fileCache[file_path];
	if (cache_data) {
		res.send(cache_data);
	}
	fs.exists(file_path, function(exists) {
		if (exists) {
			fs.readFile(file_path, function(err, data) {
				if (err) {
					res.send(502, err.message);
				} else {
					res.send(data);
				}
			});
		} else {
			res.send(404, file_404)
		}
	});
});

http.listen(port);
console.log("HTTP服务开启在" + port + "端口上。");